package com.ylkj.patient.ui.activities;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.examination.mlib.baseold.AnswerRecommendDoctorEntity;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.dialog.dialog.InquiryDialog;
import com.examination.mlib.interfaceapi.HomeBackApi;
import com.examination.mlib.interfaceapi.MineBackApi;
import com.examination.mlib.manager.PermissionManager;
import com.examination.mlib.bean.FaqEntity;
import com.examination.mlib.utils.LocationUtils;
import com.examination.mlib.view.preview.PreviewLoader;
import com.example.homemodule.model.bean.HomepageEntity;
import com.example.homemodule.HomeUrl;
import com.example.homemodule.utils.HomeUtils;
import com.example.homemodule.view.ui.NewHomeFragment;
import com.example.loginmodule.utils.LoginUtils;
import com.example.messagemodule.MessageHelper;
import com.example.messagemodule.utils.MessageUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.examination.mlib.baseold.AnswerResultEntity;
import com.examination.mlib.baseold.HomePopupEntity;
import com.previewlibrary.ZoomMediaLoader;
import com.yilijk.base.AppBase;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.core.NetWorkService;
import com.yilijk.base.network.core.RetrofitManager;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.oss.UploadOssUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.RomUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;
import com.yljk.live.common.utils.MediaCountyManager;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.examination.mlib.utils.DialogUtils;
import com.examination.mlib.utils.LoginThenRouterUtils;
import com.ylkj.patient.BuildConfig;
import com.ylkj.patient.MainApplication;
import com.ylkj.patient.R;
import com.ylkj.patient.adapter.PhoneAdapter;
import com.ylkj.patient.entity.TabEntity;
import com.ylkj.patient.entity.VersionEntity;
import com.ylkj.patient.utils.AMapLocationUtils;
import com.ylkj.patient.utils.AppReactUtils;
import com.ylkj.patient.utils.PushUtils;
import com.ylkj.patient.utils.UpgradeManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import crossoverone.statuslib.StatusUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


import static com.examination.mlib.constants.AllStringConstants.getQuality;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_ASK;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_BANNER;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_CART;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_DOCTOR;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_FOLLOW;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_IM;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_MINE;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_ORDER;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_PRESCRIPTION;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_QUALIFY;
import static com.example.minemodule.MineConstants.LOGOUT_RESULT;
import static com.example.minemodule.MineConstants.SETTING_REQUEST_ID;

/**
 * app首页
 */
@Route(path = ARouterConstants.MAIN_ACTIVITY)
public class MainActivity extends ModuleBaseActivity {

    private static int MAX_TOP = 320;
    private static int MAX_LEFT = 160;

    private FragmentManager fragmentManager;
    public CommonTabLayout commontab;
    private Fragment NewHomeFragment = null;
    private Fragment imFragment = null;
    private Fragment mallFragment = null;
    private Fragment cartFragment = null;
    private Fragment myFragment = null;
    private FrameLayout imLayout;
    private FrameLayout imLayoutContent;
    private ImageView custom_close;

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ArrayList<CustomTabEntity> tabs = new ArrayList<>();

    private PopupWindow popWindow;

    private boolean clickormove = true;  //点击或拖动，点击为true，拖动为false
    private int downX, downY;   //按下时的X，Y坐标
    private int lastX, lastY;    //保存手指点下的点的坐标
    private int lastLeft, lastTop;    //记录上次滑动的左边距和上边距
    final static int IMAGE_SIZE = 220;
    private int screenWidth = 0, screenHeight = 0;
    private FrameLayout main_layout;
    //双击退出
    private static boolean isExit = false;

    private boolean isScrolling = false;
    private final int MESSAGE_SHOW_IM = 1001;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_SHOW_IM: {
                    isScrolling = false;
                    showImLayout();
                }
            }
        }
    };

    private RelativeLayout mainTabLayoutRl;
    private Dialog dialogHome, dialogHomeAnswer, dialogWrongAnswer, dialogRedEnvelopes, dialogProtocal;

    private BroadcastReceiver showPopMessageBroadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AllStringConstants.BroadcastReceiver.equals(intent.getAction())) {
                if (intent.getBooleanExtra("showPop", false)) {
                    if (commontab.getCurrentTab() != 1 && !newMessagePop.isShowing()) {
                        //只展示Im信息 如果有
                        getHomePagePatientPopup(false, true, true, false, true);
//                        NetWorkUtils.get(MainActivity.this, DevicesUtils.getCurrentUrl() + AllStringConstants.popUp, new NetWorkCallBack() {
//                            @Override
//                            public void onSuccess(String resultMsg, int code) {
//                                if (code == 200) {
//                                    PopUpEntity popUpEntity = new Gson().fromJson(resultMsg, PopUpEntity.class);
//                                    if (popUpEntity.isResult() && popUpEntity.getData() != null) {
//                                        if (popUpEntity.getData().isNeedPopUp()) {
////                                    newMessagePopContent.setText(popUpEntity.getData().getContent());
//                                            if (!TextUtils.isEmpty(popUpEntity.getData().getContent())) {
//                                                showNewMessagePop(popUpEntity.getData().getContent());
//                                            } else {
//                                                showNewMessagePop("您的问诊有新消息回复，请及时查看。");
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//
//                            @Override
//                            public void onFailure(String failureMsg) {
//
//                            }
//
//                            @Override
//                            public void onException(Exception exceptionMsg, int code) {
//
//                            }
//                        });
                    }
                }

            } else if (AllStringConstants.BroadcastLogin.equals(intent.getAction())) {

            }
        }
    };


    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocationUtils.getInstance().setaMapLocation(null);
        LocationUtils.getInstance().setWhCityBean(null);
        //HttpLog悬浮球
        if (ProjectConfigure.isOpenHttpLog) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //检查是否已经授予权限
                if (!Settings.canDrawOverlays(MainActivity.this)) {
                    //若未授权则请求权限
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, 2202);
                } else {


                }
            }


        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
//        PermissionManager.getInstance()
//                .get(MainActivity.this)
//                .requestPermissions(
//                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}
//                        ,
//                        new String[]{"允许应用使用位置权限"})
//                .requestCodes(2001)
//                .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
//                    @Override
//                    public void noM() {
//
//                    }
//
//                    @Override
//                    public void granted() {
//                        //上传图片
//                        AMapLocationUtils.saveLocalInfo(MainActivity.this);
//                    }
//
//                    @Override
//                    public void denied() {
//
//                    }
//                })
//                .request();
        //沉浸式设置
        StatusUtil.setSystemStatus(this, true, false);
        MediaCountyManager.getInstance().attachToRoot(this);
        if (ProjectConfigure.Open.isOpenUnlinePush) {
            PushUtils.HMSUtils.getHMSPushToken(AppBase.getApplication());
        }
    }

    @Override
    public int bondLayout() {
        return R.layout.activity_main;
    }

    public View getMainTabLayoutView() {
        return mainTabLayoutRl;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AllStringConstants.BroadcastReceiver);
        intentFilter.addAction(AllStringConstants.BroadcastLogin);
        registerReceiver(showPopMessageBroadcast, intentFilter);
        imLayout = findViewById(R.id.im_layout_ll);
        imLayoutContent = findViewById(R.id.imLayout);
        main_layout = findViewById(R.id.main_layout);
        //初始设置一个layoutParams
//        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215), (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215));
//        layoutParams.gravity = Gravity.BOTTOM | Gravity.END;
//        imLayout.setLayoutParams(layoutParams);
        getImLayoutParam();
        MAX_TOP = ScreenUtils.dip2px(MainActivity.this, 130);
        screenHeight = ScreenUtils.getScreenHeight();
        screenWidth = ScreenUtils.getScreenWidth();
        custom_close = findViewById(R.id.custom_close);
        //底部导航栏
        fragmentManager = getSupportFragmentManager();
        commontab = findViewById(R.id.commontab);
        mainTabLayoutRl = findViewById(R.id.rl_tl_main);
        //添加底部导航icon
        tabs.clear();
        tabs.add(new TabEntity(R.mipmap.index_active, R.mipmap.index, "首页"));
        tabs.add(new TabEntity(R.mipmap.im_active, R.mipmap.im, "消息"));
        if (ProjectConfigure.Open.isShowMall) {
            tabs.add(new TabEntity(R.mipmap.icon_mall_select, R.mipmap.icon_mall, "商城"));
        }
        tabs.add(new TabEntity(R.mipmap.cart_active, R.mipmap.cart, "药品清单"));
        tabs.add(new TabEntity(R.mipmap.my_active, R.mipmap.my, "我的"));
        commontab.setTabData(tabs);
        //获取主页/im消息页 fragmetn
        NewHomeFragment = (Fragment) ARouter.getInstance().build(ARouterConstants.HOME_FRAGMENT).navigation();
        if (NewHomeFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, NewHomeFragment).commit();
            fragments.add(NewHomeFragment);
        }
        imFragment = (Fragment) ARouter.getInstance().build(ARouterConstants.IM_FRAGMENT).navigation();
        if (imFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, imFragment).commit();
            fragments.add(imFragment);
        }
        if (ProjectConfigure.Open.isShowMall) {
            mallFragment = (Fragment) ARouter.getInstance().build(ARouterConstants.MALL_FRAGMENT).navigation();
            if (mallFragment != null) {
                fragmentManager.beginTransaction()
                        .add(R.id.main_viewpager, mallFragment).commit();
                fragments.add(mallFragment);
            }
        }

        cartFragment = (Fragment) ARouter.getInstance().build(ARouterConstants.CART_FRAGMENT).navigation();
        if (cartFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, cartFragment)
                    .commit();
            fragments.add(cartFragment);
        }
        myFragment = (Fragment) ARouter.getInstance().build(ARouterConstants.MineFragment).navigation();
        if (myFragment != null) {
            fragmentManager.beginTransaction()
                    .add(R.id.main_viewpager, myFragment)
                    .commit();
            fragments.add(myFragment);
        }
        fragmentManager.beginTransaction().commit();
        initEvent();
        viewpagerChange(0, -1);
        commontab.setCurrentTab(0);
    }

    @Override
    public void initData() {
        initNewMessagePop();
        getVersionCode();

//        getHomePagePatientPopup();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING_REQUEST_ID && resultCode == LOGOUT_RESULT) {
            boolean b = SharedPreferencesUtils.getInstance().removeAll();
            if (b) {
                MineBackApi mineBackApi = (MineBackApi) ARouter.getInstance().build(ARouterConstants.MineModuleImpl).navigation();
                mineBackApi.logoutLive();
                if (MessageUtils.logoutIM()) {
                    ARouter.getInstance().build(ARouterConstants.CenterActivity).navigation();
                    finish();
                }

            }
        }

    }

    /**
     * 首页弹窗接口
     *
     * @param isShowAgree    是否展示协议更新弹窗
     * @param isShowActivity 是否展示首页活动弹窗
     * @param isShowIm       是否展示IM消息弹窗
     * @param imCheck        IM消息校验 只有传true时 才校验IM弹窗
     */
    public void getHomePagePatientPopup(boolean isShowAgree, boolean isShowInquiry, boolean isShowIm, boolean isShowActivity, boolean imCheck) {
        RequestParams jsonObject = new RequestParams();
        JSONArray jsonArray = new JSONArray();
        jsonArray.put("yhzcjfwxy");
        jsonArray.put("flsmjyszccs");
//            jsonArray.put("riskConfirm");
        jsonObject.put("documentNoList", jsonArray.toString());
        jsonObject.put("imCheck", imCheck);
        jsonObject.put("terminal", DevicesUtils.getTerminal());
        /**
         * {"status":"200",
         *  "data":
         *      {"agreementPopupSign":false,
         *       "imPopupSign":true,
         *       "activityPopupSign":false,
         *       "content":"您的问诊有新的消息，请及时查看",
         *       "activityPopupImage":null,
         *       "activityJumpType":null,
         *       "activityJumpUrl":null
         *       }
         * }
         */
        HttpUtils.get(AllStringConstants.getHomepagePatientPopup, jsonObject, new HttpCallBack<HomePopupEntity>() {
            @Override
            public void onSuccess(HomePopupEntity homePopupEntity, int i) {
                HomePopupEntity.Data data = homePopupEntity.getData();
                if (data.isAgreementPopupSign() && isShowAgree) {
                    if (dialogProtocal != null) {
                        if (dialogProtocal.isShowing()) {
                            dialogProtocal.dismiss();
                        }
                    }
                    dialogProtocal = DialogUtils.showProtocalDialog(MainActivity.this, new DialogUtils.ProtocalDialogListener() {
                        @Override
                        public void onAgreement() {
                            isShowInquiryDialog(data, isShowInquiry, isShowIm, isShowActivity);
                        }
                    });
                } else {
                    isShowInquiryDialog(data, isShowInquiry, isShowIm, isShowActivity);

                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });

    }

    /**
     * 首页活动弹窗
     */
    private void isShowActivityDialog(HomePopupEntity.Data data) {
        if (data.isActivityPopupSign()) {
            //首页答题弹窗
            if (data.getHomePagePopupAnswerVO() != null && !TextUtils.isEmpty(data.getHomePagePopupAnswerVO().getPlatformActivitiesSubjectId())) {
                if (dialogHomeAnswer != null) {
                    if (dialogHomeAnswer.isShowing()) {
                        dialogHomeAnswer.dismiss();
                    }
                }
                dialogHomeAnswer = DialogUtils.showHomeAnswerDialog(MainActivity.this, HomeUrl.answerResultFilled, data.getHomePagePopupAnswerVO(), new DialogUtils.HomeAnswerListener() {
                    @Override
                    public void onHistoryClick(HomePopupEntity.HomePagePopupAnswerVO answerVO) {
                        Bundle bundle = new Bundle();
                        bundle.putString("platformActivitiesId", answerVO.getPlatformActivitiesId());
                        HomeUtils.push(MainActivity.this, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.Rumor, bundle);
                    }

                    @Override
                    public void onBingo(AnswerResultEntity.Data data) {
                        try {
                            ((NewHomeFragment) NewHomeFragment).refreshHomeData();
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                        }
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("platformActivitiesId", data.getPlatformActivitiesId());
                            jsonObject.put("subjectId", data.getSubjectId());
                            if (dialogRedEnvelopes != null) {
                                if (dialogRedEnvelopes.isShowing()) {
                                    dialogRedEnvelopes.dismiss();
                                }
                            }
                            dialogRedEnvelopes = DialogUtils.showRedEnvelopes(MainActivity.this, jsonObject, HomeUrl.claimedRedEnvelope, new DialogUtils.RedEnvelopesListener() {
                                @Override
                                public void onClose() {

                                }

                                @Override
                                public void useRmb(AnswerRecommendDoctorEntity.Data data) {
                                    if (data != null && !TextUtils.isEmpty(data.getDoctorId())) {
                                        //快速购药
                                        Bundle bundle = new Bundle();
                                        bundle.putString("doctorId", data.getDoctorId());
                                        HomeUtils.push(MainActivity.this, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Drug, bundle);
                                    } else {
//                                        HomeUtils.goHome(HealthAnswerActivity.this);
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onWrong() {

                        try {
                            ((NewHomeFragment) NewHomeFragment).refreshHomeData();
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                        }

                        if (dialogWrongAnswer != null) {
                            if (dialogWrongAnswer.isShowing()) {
                                dialogWrongAnswer.dismiss();
                            }
                        }
                        dialogWrongAnswer = DialogUtils.showWrongAnswer(MainActivity.this, DialogUtils.ENVELOPES_ANSWER_WRONG, new DialogUtils.WrongAnswerListener() {
                            @Override
                            public void onDismiss() {

                            }
                        });
                    }

                    @Override
                    public void onDismiss() {
                        addPatientPopupLog(data.getPatientPopupId());
                    }
                });
            } else {
                if (TextUtils.isEmpty(data.getActivityPopupImage())) {
                    return;
                }
                if (dialogHome != null) {
                    if (dialogHome.isShowing()) {
                        dialogHome.dismiss();
                    }
                }
                dialogHome = DialogUtils.showHomeDialog(MainActivity.this, data.getActivityPopupImage(), new DialogUtils.HomeActivityDialogListener() {
                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onActivityClick() {
                        String jumpUrl = data.getActivityJumpUrl();
                        if (!TextUtils.isEmpty(jumpUrl)) {
                            if ("1".equals(data.getActivityJumpType())) {
                                if (jumpUrl.startsWith("http")) {
                                    ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
//                                                            .withString("title", bannerBean.getTitle())
                                            .withBoolean("ishtml", false)
                                            .withString("url", jumpUrl)
                                            .withBoolean("isShowLoading", true).navigation();
                                } else {
                                    jumpUrl = "com.patient.scheme:jumpToDrug?id=${doctorId}&tabType=o2o";
                                    jumpUrl = jumpUrl.replaceFirst("//", "");
                                    jumpUrl = jumpUrl.replaceFirst(":", "://");
                                    Uri uri = Uri.parse(jumpUrl);
                                    String path = uri.getLastPathSegment();
                                    String host = uri.getHost();
                                    if (TextUtils.isEmpty(path)) {
                                        path = host;
                                    }
                                    switch (path) {
                                        case "jumpToDrug":
                                            if (uri.getQueryParameter("tabType").equals("o2o")) {
                                                if (NewHomeFragment != null) {
                                                    NewHomeFragment h = (NewHomeFragment) NewHomeFragment;
                                                    h.toDrugListOTO();
                                                }
                                            }
                                            break;
                                    }
                                }
                            } else if ("2".equals(data.getActivityJumpType()) && !TextUtils.isEmpty(jumpUrl)) {
                                Bundle bundle = new Bundle();
                                bundle.putString("promotionId", jumpUrl);
                                LoginUtils.push(MainActivity.this, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Promotion, bundle);
                            } else {

                            }
                        }


                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("name", "首页弹窗跳转");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onDismiss() {
//                    isShowImDialog(data, isShowIm);
                        addPatientPopupLog(data.getPatientPopupId());

                    }
                });
            }
        } else {
//            isShowImDialog(data, isShowIm);
        }
    }

    /**
     * 取消弹窗日志自动记录功能
     * 改为前端调用日志记录
     *
     * @param patientPopupId 弹窗接口返回的弹窗ID
     */
    private void addPatientPopupLog(String patientPopupId) {
        if (TextUtils.isEmpty(patientPopupId)) {
            return;
        }
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("patientPopupId", patientPopupId);
        HttpUtils.get(AllStringConstants.addPatientPopupLog, jsonObject, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {

            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    private void isShowInquiryDialog(HomePopupEntity.Data data, boolean isShowInquiry, boolean isShowIm, boolean isShowActivity) {
        if (data != null && data.isRemindPopupSign() && isShowInquiry) {
            InquiryDialog inquiryDialog = new InquiryDialog(this);
            inquiryDialog.setMessageSignContent(data.getRemindContent());
            inquiryDialog.setListener(new InquiryDialog.ClickListener() {
                @Override
                public void go() {
                    if (data.getHomePagePopupRemindVO() != null) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", data.getHomePagePopupRemindVO().getOrderId());
                        bundle.putString("regularNo", data.getHomePagePopupRemindVO().getRegularNo());
                        if (!TextUtils.isEmpty(data.getHomePagePopupRemindVO().getRegularNo())) {
                            AppReactUtils.INSTANCE.push(MainActivity.this, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.OrderDateBuy, bundle);
                        } else {
                            AppReactUtils.INSTANCE.push(MainActivity.this, KitArouterConstants.MY_BUNDLE, KitArouterConstants.Mine.MyOrderDrugDetails, bundle);
                        }
                    }
                    isShowImDialog(data, isShowActivity, isShowIm);
                }

                @Override
                public void close() {
                    isShowImDialog(data, isShowActivity, isShowIm);
                }
            });
            inquiryDialog.show();
        } else {
            isShowImDialog(data, isShowActivity, isShowIm);
        }
    }


    /**
     * IM消息弹窗
     *
     * @param isShowIm       是否展示IM消息弹窗
     * @param isShowActivity 是否展示首页活动弹窗
     */
    private void isShowImDialog(HomePopupEntity.Data data, boolean isShowActivity, boolean isShowIm) {
        if (data != null && data.isImPopupSign() && isShowIm) {
            if (!TextUtils.isEmpty(data.getContent())) {
                showNewMessagePop(data.getContent(), data, isShowActivity);
            } else {
                showNewMessagePop("您的问诊有新消息回复，请及时查看。", data, isShowActivity);
            }
        } else {
            if (isShowActivity && data != null) {
                isShowActivityDialog(data);
            }
        }
    }

    private int imLayoutT = 0;
    private int imLayoutL = 0;
    private int imLayoutW = 0;
    private int imLayoutH = 0;

    public void getImLayoutParam() {
        imLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                imLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imLayout.getLayoutParams();
                imLayoutT = imLayout.getTop();
                imLayoutL = imLayout.getLeft();
                imLayoutW = layoutParams.width;
                imLayoutH = layoutParams.height;
            }
        });

    }

    public void hideImLayout() {

        if (!isScrolling) {
            isScrolling = true;
            if (imLayout.getLeft() < (int) (screenWidth * 0.5)) {
                Animation animation = AnimationUtils.loadAnimation(this, R.anim.im_layout_hide_anim_left);
                imLayoutContent.startAnimation(animation);
            } else {
                Animation animation = AnimationUtils.loadAnimation(this, R.anim.im_layout_hide_anim);
                imLayoutContent.startAnimation(animation);
            }
        }
        handler.removeMessages(MESSAGE_SHOW_IM);
        handler.sendEmptyMessageDelayed(MESSAGE_SHOW_IM, 100);

    }

    public void showImLayout() {
        if (imLayout.getLeft() < (int) (screenWidth * 0.5)) {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.im_layout_show_anim_left);
            imLayoutContent.startAnimation(animation);
        } else {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.im_layout_show_anim);
            imLayoutContent.startAnimation(animation);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ((NewHomeFragment) NewHomeFragment).refreshHomeData();

        LoginThenRouterUtils routerUtils = LoginThenRouterUtils.getInstance();
        LoginThenRouterUtils.RouterBean routerBean = routerUtils.getBean();
        if (routerBean != null) {
            switch (routerBean.getType()) {
                case TYPE_QUALIFY: {
                    LoadingUtils.getLoadingUtils(MainActivity.this).showLoading();
                    RequestParams params = null;
                    try {
                        params = new RequestParams(((JSONObject) routerBean.getParams()).toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    HttpUtils.get(getQuality, params, new HttpCallBack<FaqEntity>() {
                        @Override
                        public void onSuccess(FaqEntity entity, int i) {
                            if (entity != null && "200".equals(entity.getCode())) {
                                ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
                                        .withString("title", entity.getData().getTitle())
                                        .withString("url", entity.getData().getContent())
                                        .withBoolean("ishtml", true)
                                        .navigation();
                            }
                            LoadingUtils.getLoadingUtils(MainActivity.this).dismissLoading();
                        }

                        @Override
                        public void onFailure(String s, int i) {
                            LoadingUtils.getLoadingUtils(MainActivity.this).dismissLoading();

                        }
                    });

                    break;
                }
                case TYPE_ORDER:
                case TYPE_ASK:
                case TYPE_DOCTOR:
                case TYPE_PRESCRIPTION:
                case TYPE_FOLLOW: {
                    if (routerBean.getParams() != null) {
                        HomeUtils.push(MainActivity.this, routerBean.getPluginId(), routerBean.getComponentName(), (Bundle) routerBean.getParams());
                    } else {
                        HomeUtils.push(MainActivity.this, routerBean.getPluginId(), routerBean.getComponentName());
                    }
                    break;
                }
                case TYPE_BANNER: {
                    if (routerBean.getParams() != null && routerBean.getParams() instanceof HomepageEntity.DataBean.HomeAdBannerBean) {
                        HomepageEntity.DataBean.HomeAdBannerBean bannerBean = (HomepageEntity.DataBean.HomeAdBannerBean) routerBean.getParams();
                        if (bannerBean.isRedirect() && !TextUtils.isEmpty(bannerBean.getRedirectUrl())) {
                            //跳转活动页面
                            String h5Url = bannerBean.getRedirectUrl();
                            if (!TextUtils.isEmpty(h5Url) && (h5Url.startsWith("http") || h5Url.startsWith("https"))) {
                                String passportId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, "");
                                String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, "");
                                String url = h5Url.replace("${passportId}", passportId + "");
                                url = url.replace("${token}", token + "");
                                url = url.replace("${timestamp}", System.currentTimeMillis() + "");

                                if (url.startsWith("http") || url.startsWith("https")) {
                                    ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
                                            .withString("title", bannerBean.getTitle())
                                            .withBoolean("ishtml", false)
                                            .withString("url", url)
                                            .withBoolean("isShowLoading", true).navigation();
                                }
                            }


                        }
                    }
                    break;
                }

                case TYPE_IM: {
                    commontab.setCurrentTab(1);
                    viewpagerChange(1, -1);
                    break;
                }
                case TYPE_CART: {
                    if (ProjectConfigure.Open.isShowMall) {
                        commontab.setCurrentTab(3);
                        viewpagerChange(3, -1);
                    } else {
                        commontab.setCurrentTab(2);
                        viewpagerChange(2, -1);
                    }
                    break;
                }
                case TYPE_MINE: {
                    if (ProjectConfigure.Open.isShowMall) {
                        commontab.setCurrentTab(4);
                        viewpagerChange(4, -1);
                    } else {
                        commontab.setCurrentTab(3);
                        viewpagerChange(3, -1);
                    }
                    break;
                }
            }

            routerUtils.setBean(null);
        }

    }

    @Override
    public void initEvent() {

        moveButton();
//底部导航的点击监听
        commontab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                imLayout.setVisibility(View.INVISIBLE);
                switch (position) {
                    case 0: {
                        //TODO 埋点
                        ClickUtils.sendEvent(ClickApi.App.Tab1, MainActivity.this, "首页Tab点击");
                        viewpagerChange(0, -1);
                        imLayout.setVisibility(View.VISIBLE);
                        getHomePagePatientPopup(true, true, false, true, false);
                        break;
                    }
                    case 1: {
                        //TODO 埋点
                        ClickUtils.sendEvent(ClickApi.App.Tab2, MainActivity.this, "消息Tab点击");
                        String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
                        String account_mobile = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_mobile, null);
                        if (token == null && account_mobile == null) {
                            LoginUtils.push(MainActivity.this, KitArouterConstants.LOGIN_DOCTORBUNDLE, KitArouterConstants.Login.Index);
                            commontab.setCurrentTab(0);
                            LoginThenRouterUtils.RouterBean bean = new LoginThenRouterUtils.RouterBean(
                                    TYPE_IM, "", "", null
                            );
                            LoginThenRouterUtils.getInstance().setBean(bean);
                            return;
                        }
                        viewpagerChange(1, -1);

                        break;
                    }
                    case 2: {
                        //TODO 埋点
                        if (ProjectConfigure.Open.isShowMall) {
                            switchMall();
                        } else {
                            if (switchCart()) return;
                        }
                        viewpagerChange(2, -1);
                        break;
                    }
                    case 3: {
                        if (ProjectConfigure.Open.isShowMall) {
                            if (switchCart()) return;
                        } else {
                            if (switchMine()) {
                                return;
                            }
                            imLayout.setVisibility(View.VISIBLE);
                        }
                        viewpagerChange(3, -1);
                        break;
                    }
                    case 4: {
                        if (switchMine()) {
                            return;
                        }
                        imLayout.setVisibility(View.VISIBLE);
                        viewpagerChange(4, -1);
                        break;
                    }
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        //展开收起popupwindows
        imLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome, MainActivity.this, "联系客服点击");
//                AGConnectCrash.getInstance().testIt(MainActivity.this);
                if (clickormove) {
                    if (popWindow == null) {
                        initPopWindow(imLayout);
                    } else {
                        if (popWindow.isShowing()) {
                            popWindow.dismiss();
                        } else {
                            showImPopWindow();
                        }
                    }
                }
            }
        });
        imLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (BuildConfig.OPEN_RN_DEBUG) {
                    startActivity(new Intent(MainActivity.this, DebugRnActivity.class));
                }
                return true;
            }
        });

        //关闭客服
        custom_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome_close, MainActivity.this, "关闭客服");
                imLayout.setVisibility(View.GONE);
            }
        });
    }

    private boolean switchMine() {
        //TODO 埋点
        ClickUtils.sendEvent(ClickApi.App.Tab5, MainActivity.this, "我的Tab点击");
        String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
        String account_mobile = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_mobile, null);
        if (token == null && account_mobile == null) {
            LoginUtils.push(MainActivity.this, KitArouterConstants.LOGIN_DOCTORBUNDLE, KitArouterConstants.Login.Index);
            commontab.setCurrentTab(0);
            LoginThenRouterUtils.RouterBean bean = new LoginThenRouterUtils.RouterBean(
                    TYPE_MINE, "", "", null
            );
            LoginThenRouterUtils.getInstance().setBean(bean);
            return true;
        }
        return false;
    }

    private boolean switchCart() {
        //TODO 埋点
        ClickUtils.sendEvent(ClickApi.App.Tab4, MainActivity.this, "药品清单Tab点击");
        String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
        String account_mobile = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_mobile, null);
        if (token == null && account_mobile == null) {
            LoginUtils.push(MainActivity.this, KitArouterConstants.LOGIN_DOCTORBUNDLE, KitArouterConstants.Login.Index);
            commontab.setCurrentTab(0);
            LoginThenRouterUtils.RouterBean bean = new LoginThenRouterUtils.RouterBean(
                    TYPE_CART, "", "", null
            );
            LoginThenRouterUtils.getInstance().setBean(bean);
            return true;
        }
        return false;
    }

    private void switchMall() {
        ClickUtils.sendEvent(ClickApi.App.Tab3, MainActivity.this, "商城Tab点击");
    }

    private void onDismissedImPopWindow() {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imLayout.getLayoutParams();
        if (imLayout.getLeft() < (int) (screenWidth * 0.5)) {
            layoutParams.leftMargin = 0;
            imLayout.setLayoutParams(layoutParams);
        } else {

        }
    }

    /**
     * 新消息弹窗
     */
    void showNewMessagePop(String content, HomePopupEntity.Data data, boolean isShowActivityDialog) {
        newMessagePopClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newMessagePop.dismiss();
                if (isShowActivityDialog && data != null) {
                    isShowActivityDialog(data);
                }
            }
        });
        handler.post(new Runnable() {
            @Override
            public void run() {
                newMessagePopContentTv.setText(content);
                newMessagePop.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
//                CommonUtils.setBackgroundAlpha(newMessagePop,MainActivity.this,0.3f);
            }
        });
    }

    /**
     * 新消息pop
     */

    private PopupWindow newMessagePop;
    private View newMessagePopView;
    private ImageView newMessagePopClose;
    private TextView newMessagePopCheck;
    private TextView newMessagePopContentTv;

    private void initNewMessagePop() {
        newMessagePop = new PopupWindow();
        newMessagePopView = LayoutInflater.from(this).inflate(R.layout.new_message_pop, null);
        newMessagePopClose = (ImageView) newMessagePopView.findViewById(R.id.new_message_pop_close);
        newMessagePopCheck = (TextView) newMessagePopView.findViewById(R.id.new_message_pop_check);
        newMessagePopContentTv = newMessagePopView.findViewById(R.id.tv_message_content);

        newMessagePop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        newMessagePop.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
        newMessagePop.setContentView(newMessagePopView);

        newMessagePop.setFocusable(false);
        newMessagePop.setOutsideTouchable(false);
        newMessagePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
        newMessagePopClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newMessagePop.dismiss();
            }
        });
        newMessagePopCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                commontab.setCurrentTab(1);
                viewpagerChange(1, -1);
                imLayout.setVisibility(View.GONE);
                commontab.setCurrentTab(1);
                newMessagePop.dismiss();
            }
        });
    }

    private void initPopWindow(View v) {
        View view = LayoutInflater.from(this).inflate(com.ylkj.patientdrug.R.layout.item_popup, null, false);
        LinearLayout tocontact_layout = (LinearLayout) view.findViewById(com.ylkj.patientdrug.R.id.tocontact_layout);
        LinearLayout tophone_layout = (LinearLayout) view.findViewById(com.ylkj.patientdrug.R.id.tophone_layout);
        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

//        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                onDismissedImPopWindow();
            }
        });

        showImPopWindow();
        //在线客服
        tocontact_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome_online, MainActivity.this, "在线客服点击");
                String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
                String account_mobile = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_mobile, null);
                if (token == null && account_mobile == null) {
                    LoginUtils.push(MainActivity.this, KitArouterConstants.LOGIN_DOCTORBUNDLE, KitArouterConstants.Login.Index);
                    commontab.setCurrentTab(0);
                    return;
                }
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.page_custome, MainActivity.this, "在线客服跳转");
                ARouter.getInstance().build(ARouterConstants.ContractWebviewActivity)
                        .withString("title", "在线客服")
                        .withBoolean("isShowLoading", true).navigation();
            }
        });
        //电话咨询
        tophone_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome_phone, MainActivity.this, "电话咨询点击");
                ArrayList<String> tels = new ArrayList<>();
                tels.add("4000867818");
                openPhoneView(tels);
                popWindow.dismiss();
            }
        });
    }

    private void showImPopWindow() {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) imLayout.getLayoutParams();
        if (imLayout.getLeft() < (int) (screenWidth * 0.5)) {
            layoutParams.leftMargin = ScreenUtils.dip2px(MainActivity.this, 60);
            imLayout.setLayoutParams(layoutParams);
        } else {

        }
        popWindow.showAsDropDown(imLayout, -ScreenUtils.dip2px(MainActivity.this, 60), -(imLayoutH + ScreenUtils.dip2px(MainActivity.this, 90)));

//      if (layoutParams.leftMargin == 0) {
//          //客服在左邊
//          popWindow.showAsDropDown(imLayout, -ScreenUtils.dip2px(MainActivity.this, 50), -(imLayoutH + ScreenUtils.dip2px(MainActivity.this, 90)));
//      } else {
//          //客服在右边
//          popWindow.showAsDropDown(imLayout, -imLayoutW + ScreenUtils.dip2px(MainActivity.this, 20), -(imLayoutH + ScreenUtils.dip2px(MainActivity.this, 80)));
//      }

        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
//        popWindow.showAsDropDown(imLayout, 0 - (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.160), 0 - (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.45));

    }


    void moveButton() {
        //控制客服聊天拖动
        imLayout.setOnTouchListener(new View.OnTouchListener() {//设置按钮被触摸的时间

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View view, MotionEvent event) {


                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        //将点下的点的坐标保存
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        downX = lastX;
                        downY = lastY;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        //计算出需要移动的距离
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        //将移动距离加上，现在本身距离边框的位置
                        int left = view.getLeft() + dx;
                        int top = view.getTop() + dy;
                        int right = view.getRight() + dx;
                        int bottom = view.getBottom() + dy;
                        if (left < 0) {
                            left = 0;
                            right = left + view.getWidth();
                        }
                        if (right > screenWidth) {
                            right = screenWidth;
                            left = right - view.getWidth();
                        }
                        if (top < 0) {
                            bottom = top + view.getHeight();
                        }
//                        if (bottom > (screenHeight - mainTabLayoutRl.getMeasuredHeight())) {
                        if (top > imLayoutT) {
                            top = imLayoutT;
                            bottom = top + view.getHeight();
                        }
                        //获取到layoutParams然后改变属性，在设置回去
                        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view
                                .getLayoutParams();
                        layoutParams.gravity = 0;
//                        layoutParams.height = IMAGE_SIZE;
//                        layoutParams.width = IMAGE_SIZE;
//                        layoutParams.height = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215);
//                        layoutParams.width = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215);
                        layoutParams.height = imLayoutH;
                        layoutParams.width = imLayoutW;

                        layoutParams.leftMargin = left;
                        layoutParams.topMargin = top;
                        view.setLayoutParams(layoutParams);
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        lastTop = top;
                        lastLeft = left;
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP: // 弹起事件
                        //判断是单击事件或是拖动事件，位移量大于5则断定为拖动事件
                        if (Math.abs((int) (event.getRawX() - downX)) > 5 || Math.abs((int) (event.getRawY() - downY)) > 5) {
                            clickormove = false;
//                            if (lastTop < MAX_TOP || lastLeft < MAX_LEFT) {//需要判断滑到最顶部时 退回一定距离，给popupwindow流出空隙
                            FrameLayout.LayoutParams layoutParams1 = (FrameLayout.LayoutParams) view
                                    .getLayoutParams();
                            layoutParams1.gravity = 0;
//                            layoutParams1.height = IMAGE_SIZE;
//                            layoutParams1.width = IMAGE_SIZE;
//                            layoutParams1.height = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215);
//                            layoutParams1.width = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.215);
                            layoutParams1.height = imLayoutH;
                            layoutParams1.width = imLayoutW;

                            if (lastTop < MAX_TOP) {
//                                layoutParams1.topMargin = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.28);
                                layoutParams1.topMargin = MAX_TOP;
                            } else {
                                layoutParams1.topMargin = lastTop;
                            }
//                            if (lastLeft < MAX_LEFT) {
//                                layoutParams1.leftMargin = MAX_LEFT;
//                            } else {
//                                layoutParams1.leftMargin = lastLeft;
//                            }
//                            if (lastLeft < screenWidth / 2) {
//                            if (lastLeft < (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.5)) {
                            if (lastLeft < (int) (screenWidth * 0.5)) {
                                layoutParams1.leftMargin = 0;
                            } else {
//                                layoutParams1.leftMargin = screenWidth - IMAGE_SIZE;
//                                layoutParams1.leftMargin = (int) (getWindow().getWindowManager().getDefaultDisplay().getWidth() * 0.8);
                                layoutParams1.leftMargin = imLayoutL;
                            }
                            view.setLayoutParams(layoutParams1);
//                            }
                        } else {
                            clickormove = true;
                        }
                        break;
                }
                //刷新界面
                main_layout.invalidate();
                return false;
            }

        });
    }

    //viewpager hide show 切换显示
    public void viewpagerChange(int showPasition, int tabposition) {
        if (tabposition >= 0) {
            commontab.setCurrentTab(tabposition);
        }
        if (!fragments.isEmpty()) {
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                if (i == showPasition) {
                    fragmentManager.beginTransaction().show(fragment)
                            .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
                            .commit();
                } else {
                    fragmentManager.beginTransaction().hide(fragment)
                            .setMaxLifecycle(fragment, Lifecycle.State.STARTED).commit();
                }
            }
        } else {
            ALog.d("viewpagerChange", "fragments must not empty: ");
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(showPopMessageBroadcast);
        EventBus.getDefault().unregister(this);
        fragmentManager = null;
        fragments.clear();
        MessageHelper.getMessageHelper().unRegister();
        if (dialogHome != null) {
            if (dialogHome.isShowing()) {
                dialogHome.dismiss();
            }
            dialogHome = null;
        }
        if (dialogHomeAnswer != null) {
            if (dialogHomeAnswer.isShowing()) {
                dialogHomeAnswer.dismiss();
            }
            dialogHomeAnswer = null;
        }
        if (dialogWrongAnswer != null) {
            if (dialogWrongAnswer.isShowing()) {
                dialogWrongAnswer.dismiss();
            }
            dialogWrongAnswer = null;
        }
        if (dialogRedEnvelopes != null) {
            if (dialogRedEnvelopes.isShowing()) {
                dialogRedEnvelopes.dismiss();
            }
            dialogRedEnvelopes = null;
        }
        if (dialogProtocal != null) {
            if (dialogProtocal.isShowing()) {
                dialogProtocal.dismiss();
            }
            dialogProtocal = null;
        }
        super.onDestroy();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(String messageEvent) {
    }


    private RecyclerView phoneList;
    private TextView cancelDialog;

    private void openPhoneView(ArrayList<String> tels) {
        PopupWindow popupWindow = new PopupWindow();
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        View inflate = LayoutInflater.from(this).inflate(R.layout.phone_dialog_layout, null);
        phoneList = (RecyclerView) inflate.findViewById(R.id.phone_list);
        cancelDialog = (TextView) inflate.findViewById(R.id.cancel_dialog);
        PhoneAdapter phoneAdapter = new PhoneAdapter(R.layout.item_phone, tels);
        phoneList.setLayoutManager(new LinearLayoutManager(this));
        phoneList.setAdapter(phoneAdapter);
        phoneAdapter.notifyDataSetChanged();
        popupWindow.setContentView(inflate);
        popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.5f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
        cancelDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome_telcancel, MainActivity.this, "电话咨询取消");
                popupWindow.dismiss();
            }
        });
        phoneAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("UseCheckPermission")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //TODO 埋点
                ClickUtils.sendEvent(ClickApi.App.custome_tel, MainActivity.this, "拨打客服电话");
                PermissionManager.getInstance()
                        .get(MainActivity.this)
                        .requestPermissions(
                                new String[]{Manifest.permission.CALL_PHONE}
                                ,
                                new String[]{"允许应用使用拨打电话权限"})
                        .requestCodes(0xa1)
                        .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                            @Override
                            public void noM() {

                            }

                            @Override
                            public void granted() {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_CALL);
                                intent.setData(Uri.parse("tel:" + tels.get(position)));
//                    开启系统拨号器
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }

                            @Override
                            public void denied() {
                                ToastUtils.showShort("请允许应用使用拨打电话权限");
                            }
                        }).request();
            }
        });

    }

    /**
     * 获取最新版本号，判断是否需要更新版本
     */
    private void getVersionCode() {
        // 获得存储卡的路径
//        String sdpath = Environment.getExternalStorageDirectory().getPath();
//        String mSavePath = sdpath + "/com.ylkj.patient";
        String mSavePath = getExternalFilesDir("apk").getAbsolutePath();

        ALog.d("chen", "apk包下载路径为" + mSavePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), CommonUtils.getModuleCommonUtils().getMaptoJson(new HashMap<>()));
//        Call<ResponseBody> post = RetrofitManager.getRetrofitManager().getRetrofit().create(NetWorkService.class).post(HttpUtils.getUrl() + AllStringConstants.downApk, requestBody);
        Call<ResponseBody> post = RetrofitManager.getRetrofitManager().getRetrofit().create(NetWorkService.class).post(AllStringConstants.downApk, requestBody);
        post.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() == null) {
                        getHomePagePatientPopup(true, true, true, true, false);
                        return;
                    }
//                    if (DevicesUtils.isChannel()) {
//                        getHomePagePatientPopup(true,true, true, true, false);
//                        return;
//                    }
                    String string = response.body().string();
                    ALog.d("LAE", "onResponse: response=" + string);
                    VersionEntity versionEntity = new Gson().fromJson(string, VersionEntity.class);
                    if (versionEntity.getData() != null && Boolean.parseBoolean(versionEntity.getData().getHuawei_isstrong())) {
                        AllStringConstants.isShowReBuy = true;
                    }
//                    if (versionEntity.getCode() == 401) {
////                        isLogout = true;
//                        onRestart();
//                    }
                    if (requestResult(versionEntity.getStatus())) {
                        getHomePagePatientPopup(true, true, true, true, false);
                        return;
                    }
                    if (versionEntity.getCode() != 200) {
                        getHomePagePatientPopup(true, true, true, true, false);
                        return;
                    }
                    VersionEntity.DataBean data = new Gson().fromJson(string, VersionEntity.class).getData();

                    if (DevicesUtils.getVersionCode() >= data.getVersion()) {
                        getHomePagePatientPopup(true, true, true, true, false);
                        return;
                    }
                    UpgradeManager.UpdateFlag updateFlag = UpgradeManager.UpdateFlag.UN_UPDATE;
                    // 渠道包检查是否更新
                    if (DevicesUtils.isChannel()) {
                        if (RomUtils.isHuawei() && Boolean.parseBoolean(data.getHuawei_isstrong())) {
                            //华为手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_HUAWEI;
                        } else if (RomUtils.isXiaomi() && Boolean.parseBoolean(data.getXiaomi_isstrong())) {
                            //小米手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_XIAOMI;
                        } else if (RomUtils.isVivo() && Boolean.parseBoolean(data.getVivo_isstrong())) {
                            //VIVO手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_VIVO;
                        } else if (RomUtils.isOppo() && Boolean.parseBoolean(data.getOppo_isstrong())) {
                            //OPPO手机的渠道包是否更新
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_OPPO;
                        }

                    } else {
                        //官网是否更新
                        if (Boolean.parseBoolean(data.getGuanwang_isstrong())) {
                            updateFlag = UpgradeManager.UpdateFlag.UPDATE_FLAG_GUANWANG;
                        }
                    }
                    if (updateFlag == UpgradeManager.UpdateFlag.UN_UPDATE) {
                        getHomePagePatientPopup(true, true, true, true, false);
                        return;
                    }
                    UpgradeManager manager = new UpgradeManager(MainActivity.this, mSavePath, data.getVersion(), data.getUrl(), updateFlag, Boolean.parseBoolean(data.getIsstrong()), data.getContent());
                    manager.setListener(new UpgradeManager.UpgradeManagerListener() {
                        @Override
                        public void onUpgradeDismiss() {
                            getHomePagePatientPopup(true, true, true, true, false);
                        }
                    });
                    manager.checkUpdate();
//                    handler.sendEmptyMessage(2);
                } catch (Throwable e) {
                    getHomePagePatientPopup(true, true, true, true, false);
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                getHomePagePatientPopup(true, true, true, true, false);
            }
        });
    }

    private boolean requestResult(String code) {
        if (CommonUtils.request_code(MainActivity.this, code)) {
            return true;
        }
        return false;
    }

    private void backgroundAlpha(float f) {
        WindowManager.LayoutParams attributes = getWindow().getAttributes();
        attributes.alpha = f;
        getWindow().setAttributes(attributes);
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        ClickUtils.sendEvent("app_onshow", this, "APP热启动");

        if (commontab != null && commontab.getCurrentTab() == 0) {
            getHomePagePatientPopup(true, true, false, true, false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        UploadOssUtils.getInstance().init();
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("toJumpMain")) {
            int toJumpMain = intent.getIntExtra("toJumpMain", 0);
            viewpagerChange(toJumpMain, toJumpMain);
            setIntent(null);
        }
        if (MainApplication.homeType) {
            viewpagerChange(0, -1);
            commontab.setCurrentTab(0);
            MainApplication.homeType = false;
        }
//        getHomePagePatientPopup();
    }

    //菜单，返回键响应
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitApp();//调用双击函数
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        UploadOssUtils.getInstance().init();
    }

    /**
     * 双击退出函数
     */
    private void exitApp() {
        Timer timer = null;
        if (isExit == false) {
            isExit = true;//准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            timer = new Timer();

            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());   //获取PID
            System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2001) {
            AMapLocationUtils.saveLocalInfo(this);
        }
    }
}